import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from routes import faults
from database.db import init_db, init_sample_data
import uvicorn

# 初始化数据库
init_db()
init_sample_data()

app = FastAPI(
    title="故障管理系统", 
    description="设备故障管理系统API接口",
    version="1.0.0"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含路由
app.include_router(faults.router, prefix="/api/v1", tags=["故障管理"])

@app.get("/")
async def root():
    return {"message": "故障管理系统API服务正在运行"}

# 添加响应头中间件以确保正确的字符编码
@app.middleware("http")
async def add_charset_header(request, call_next):
    response = await call_next(request)
    # 确保响应头包含正确的字符编码
    if response.headers.get("content-type", "").startswith("application/json"):
        response.headers["content-type"] = "application/json; charset=utf-8"
    return response

if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8080, reload=True)
